//
//  SYOAuthViewController.swift
//  YANAWeibo
//
//  Created by mac on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

// 新浪微博的appkey
let WeiboAppKey = "193699117"
// 新浪微博的App Secret
let WeiboAppSecret = "2c65f693081eaf6a4ad3ca29d9a267f9"
// 回调的界面redirect_uri
let WeiboRedirect_uri = "http://www.163.com"

class SYOAuthViewController: UIViewController {
    
    private lazy var webview: UIWebView = UIWebView()
    
    //自定义view
    override func loadView() {
        view = webview
        
        webview.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置代理
        
        
        setupUI()
        //请求登陆地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_uri)"
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        
        webview.loadRequest(request)
    }
    
    private func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancleAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.title = "微博登录"
    }
    
     // MARK: 点击事件
    @objc private func cancleAction() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        webview.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '13986270679'; document.getElementById('passwd').value = '541994964'")
    }
    
    //获取accesstoken
//    private func requestAccessToken(code: String) {
//        
//        SYNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            //解析数据
//            guard let dic = response as? [String: AnyObject] else {
//                print("数据不是json格式")
//                return
//            }
//            //代码执行到此，一定是字典
//            let uerAccout = SYUserAccount(dic: dic)
//            print(uerAccout)
//            self.requestedUserInfo(uerAccout)
//            
//        }
//    }
//        let url = "https://api.weibo.com/oauth2/access_token"
//        let dict = [
//            "client_id": WeiboAppKey,
//            "client_secret": WeiboAppSecret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": WeiboRedirect_uri
//        ]
//        
//        
//        let sessionManager = AFHTTPSessionManager()
//    sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        sessionManager.POST(url, parameters: dict, progress: nil, success: { (_, response) -> Void in
//            print(response)
//            guard let diction = response as? [String: AnyObject] else {
//                print("数据不是正确的json")
//                return
//            }
//             
//            let userAccount = SYUserAccount(dic: diction)
//            print(userAccount)
//            self.requestedUserInfo(userAccount)
//         
//            }) { (_, error) -> Void in
//                print(error)
//        }
   
    
//    
//    // 获取用户信息
//    private func requestedUserInfo(userAccount: SYUserAccount) {
//        
//        SYNetWorkTools.sharedTools.requestedUserInfo(userAccount) { (response, error) -> () in
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            //判断json格式
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的json格式")
//                return
//            }
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            //归档
//            userAccount.saveUserAccount()
//            
//        }
//    }
//        let url = "https://api.weibo.com/2/users/show.json"
//        //设置参数
//        let parmams = [
//            "access_token": userAccount.access_token!,
//            "uid": "\(userAccount.uid)"
//        ]
//        
//        
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        sessionManager.GET(url, parameters: parmams, progress: nil, success: { (_, response) -> Void in
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的json数据")
//                return
//            }
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            print(userAccount)
//            
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }

        
        
        
    

}

 // MARK: - webview代理
extension SYOAuthViewController: UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else {
            return false
        }
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_uri) {
            return true
        }
        
        if let query = url.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            SYUserAccountViewModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    //  进入欢迎页面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                    
                }else{
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
            
        }else{
            //取消回调页
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false
    }
    
    //开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}






